package io.renren.modules.yst.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.constant.WxMaConstants;
import com.google.common.collect.Lists;
import com.google.common.io.Files;
import io.renren.common.utils.R;
import io.renren.modules.app.config.WxMaConfiguration;
import me.chanjar.weixin.common.bean.result.WxMediaUploadResult;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * <pre>
 *  小程序临时素材接口
 *  Created by BinaryWang on 2017/6/16.
 * </pre>
 *
 * @author <a href="https://github.com/binarywang">Binary Wang</a>
 */
@RestController
@RequestMapping("/wx/media/{appid}")
public class WxMaMediaController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 上传临时素材
     *
     * @return 素材的media_id列表，实际上如果有的话，只会有一个
     */
    @PostMapping("/upload")
    public R uploadMedia(@PathVariable String appid, HttpServletRequest request) throws WxErrorException {
//        final WxMaService wxService = WxMaConfiguration.getMaService(appid);

        CommonsMultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());

        if (!resolver.isMultipart(request)) {
            return R.ok().put("result",Lists.newArrayList());
        }

        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        Iterator<String> it = multiRequest.getFileNames();
        List<String> result = Lists.newArrayList();
        String osName = System.getProperty("os.name");
        String savepath="";
        if (osName.startsWith("Mac OS")) {
            // 苹果
            savepath="/opt/imgrepo";
        } else if (osName.startsWith("Windows")) {
            // windows
            savepath="C:\\Users\\lazyrm\\Pictures\\repo";
        } else {
            // unix or linux
            savepath="/opt/imgrepo";
        }
        while (it.hasNext()) {
            try {
                MultipartFile file = multiRequest.getFile(it.next());
                String fileName = file.getOriginalFilename();
                String sname = fileName.substring(fileName.lastIndexOf("."));
                SimpleDateFormat simpleDateFormat =new SimpleDateFormat("yyyyMMddHHmmssSSS");
                String timeStamp=simpleDateFormat.format(new Date());

                File newFile;
                if(StringUtils.isEmpty(savepath)){
                    newFile = new File(Files.createTempDir(), timeStamp+sname);
                }else{
                    newFile = new File(savepath, timeStamp+sname);
                }


                this.logger.info("filePath is ：" + newFile.toString());
                file.transferTo(newFile);

//
//
//                WxMediaUploadResult uploadResult = wxService.getMediaService().uploadMedia(WxMaConstants.KefuMsgType.IMAGE, newFile);
//                this.logger.info("media_id ： " + uploadResult.getMediaId());
                result.add("https://yst.dianpiao123.cn/imgrepo/"+timeStamp+sname);
            } catch (IOException e) {
                this.logger.error(e.getMessage(), e);
            }
        }

        return R.ok().put("result",result);
    }

    /**
     * 下载临时素材
     */
    @GetMapping("/download/{mediaId}")
    public File getMedia(@PathVariable String appid, @PathVariable String mediaId) throws WxErrorException {
        final WxMaService wxService = WxMaConfiguration.getMaService(appid);

        return wxService.getMediaService().getMedia(mediaId);
    }
}
